//
//  CO2HistoryViewController.m
//  Anyair
//
//  Created by karlcool on 14-5-26.
//  Copyright (c) 2014年 Karlcool. All rights reserved.
//

#import "CO2HistoryViewController.h"
#import "SHLineGraphView.h"
#import "SHPlot.h"
#import "LRSegmentedControl.h"

@interface CO2HistoryViewController ()

@end

@implementation CO2HistoryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithType:(int)type {
    
    if ([super init]) {
        dataType = type;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = AIR_GRAY;
    if (![LRUserManager createManager].isLogIn) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"登陆后才能查看历史记录" message:nil delegate:nil cancelButtonTitle:@"好的" otherButtonTitles:nil];
        [alert show];
    }
    
    
    LRSegmentedControl *segmented = [[LRSegmentedControl alloc]initWithFrame:CGRectMake(20, 5, 280, 28)];
    [segmented insertSegmentWithTitle:@"单次检测" atIndex:0 animated:NO];
    [segmented insertSegmentWithTitle:@"实时检测" atIndex:1 animated:NO];
    segmented.selectedSegmentIndex = 0;
    [segmented addTarget:self action:@selector(changeSegmented:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:segmented];
    
    UIView *breakLineView = [[UIView alloc]initWithFrame:CGRectMake(0, 39, 320, 0.5)];
    breakLineView.backgroundColor = BREAKLINE_GRAY;
    [self.view addSubview:breakLineView];
    //单次检测相关UI
    historyArray = [[[LRDatabaseManager createDatabase]getHistoryArrayByPhone:[LRUserManager createManager].userPhone AndType:dataType] mutableCopy];
    
    historyTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, 320, [UIScreen mainScreen].bounds.size.height-110) style:UITableViewStylePlain];
    historyTable.dataSource = self;
    historyTable.delegate = self;
    historyTable.backgroundColor = AIR_GRAY;
    historyTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    historyTable.rowHeight = 100;
    [self.view addSubview:historyTable];
    
    
    refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.view.bounds.size.height,self.view.frame.size.width, self.view.bounds.size.height)];
    refreshHeaderView.delegate = self;
    refreshHeaderView.title1 = @"释放开始更新";
    refreshHeaderView.title2 = @"下拉更新";
    refreshHeaderView.title3 = @"更新中";
    [historyTable addSubview:refreshHeaderView];
    [refreshHeaderView refreshLastUpdatedDate];
    NSString *historyType;
    //第一次自动加载历史记录
    BOOL loadHistory;
    if (dataType==0) {
        historyType = @"pm25";
    } else if (dataType==1) {
        historyType = @"co2";
        loadHistory = [[NSUserDefaults standardUserDefaults]boolForKey:@"loadCO2History"];
    } else if (dataType==2) {
        historyType = @"hcho";
    }
    
    if (!loadHistory) {
        dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
            NSDictionary *resposeDic = [[LRHttpManager createHttpManager]queryHistoryByPhone:[LRUserManager createManager].userPhone AndTime:nil AndType:historyType AndPage:@"0"];
            
            NSArray *tempArray = [resposeDic objectForKey:@"contents"];
            for (NSDictionary *tempDic in tempArray) {
                HistoryModel *tempModel = [[HistoryModel alloc]init];
                
                tempModel.historyDate = [tempDic objectForKey:@"sendtime"];
                if ([[tempDic objectForKey:@"placediy"] isEqualToString:@"无自定义地址"]) {
                    tempModel.historyAddress = [tempDic objectForKey:@"address"];
                } else {
                    tempModel.historyAddress = [tempDic objectForKey:@"placediy"];
                }
                tempModel.historyID = [tempDic objectForKey:@"\"geotable_id\""];
                if (dataType==0) {
                    tempModel.historyValue = [tempDic objectForKey:@"pm"];
                } else if (dataType==1) {
                    
                } else if (dataType==2) {
                    tempModel.historyValue = [tempDic objectForKey:@"hcho"];
                }
                
                LRDatabaseManager *manager=[LRDatabaseManager createDatabase];
                [manager.dataQueue inDatabase:^(FMDatabase *db){
                    [db open];
                    
                    BOOL result = [db executeUpdate:@"insert into HistoryTable(UserPhone,HistoryDate,HistoryValue,HistoryAddress,HistoryType) values(?,?,?,?,?)",[LRUserManager createManager].userPhone,tempModel.historyDate,tempModel.historyValue,tempModel.historyAddress,[NSNumber numberWithInt:dataType]];
                    NSLog(@"历史记录插入数据库%@",result?@"成功":@"失败");
                    [db close];
                }];
                
                NSLog(@"!!!%@",tempDic);
            }
            dispatch_async (dispatch_get_main_queue(),^{
                if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                    NSLog(@"获取历史记录成功");
                    [[NSUserDefaults standardUserDefaults]setObject:[LRTools getNowTime] forKey:@"lastHistory"];
                    historyArray = [[[LRDatabaseManager createDatabase]getHistoryArrayByPhone:[LRUserManager createManager].userPhone AndType:dataType] mutableCopy];
                    [historyTable reloadData];
                    [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"loadCO2History"];
                } else {
                    NSLog(@"获取历史记录失败");
                    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                    [self.view addSubview:shortHub];
                    [shortHub setLabelText:@"获取历史记录失败,请稍后再试"];
                    [shortHub setMode:MBProgressHUDModeText];
                    [shortHub hide:YES afterDelay:1];
                    [shortHub show:YES];
                }
                
            });
        });
        if (dataType==0) {
            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"lastPMHistory"];
        } else if (dataType==2) {
            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"lastHOCOHistory"];
        }
        
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"loadHistory"];
    }
    
    backSroll = [[UIScrollView alloc]initWithFrame:historyTable.frame];
    backSroll.delegate = self;
    backSroll.alpha = 0;
    backSroll.contentSize = CGSizeMake(320, backSroll.frame.size.height+1);
    [self.view addSubview:backSroll];
    
    //实时检测相关UI
    valueArray = [[NSMutableArray alloc]init];
    labelArray = [[NSMutableArray alloc]init];
    for (int i=0; i<47; i++) {
        
        int temp = arc4random()%2500;
        
        [valueArray addObject:[NSNumber numberWithInt:temp]];
        [labelArray addObject:[NSString stringWithFormat:@"%i",temp]];
    }
    
    scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 60, 320, 328)];
    scroll.contentSize = CGSizeMake(2105, scroll.frame.size.height);
    [backSroll addSubview:scroll];
    
    addressTextView = [[UITextView alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    addressTextView.text = @"重庆市北部新区云松北路";
    addressTextView.backgroundColor = [UIColor clearColor];
    addressTextView.scrollEnabled = NO;
    addressTextView.editable = NO;
    addressTextView.textColor = TEXT_GRAY;
    addressTextView.font = [UIFont systemFontOfSize:15];
    [backSroll addSubview:addressTextView];
    
    UIView *breakLineView1 = [[UIView alloc]initWithFrame:CGRectMake(0, 49, 320, 0.5)];
    breakLineView1.backgroundColor = BREAKLINE_GRAY;
    [addressTextView addSubview:breakLineView1];
    
    SHLineGraphView *lineGraph = [[SHLineGraphView alloc] initWithFrame:CGRectMake(-5, 0, 2105, scroll.frame.size.height)];
    
    NSDictionary *themeAttributes = @{
                                       kXAxisLabelColorKey : [UIColor lightGrayColor],
                                       kXAxisLabelFontKey : [UIFont fontWithName:@"TrebuchetMS" size:10],
                                       kYAxisLabelColorKey : [UIColor lightGrayColor],
                                       kYAxisLabelFontKey : [UIFont fontWithName:@"TrebuchetMS" size:10],
                                       kYAxisLabelSideMarginsKey : @20,
                                       kPlotBackgroundLineColorKye : [UIColor lightGrayColor]
                                       };
    lineGraph.themeAttributes = themeAttributes;
    lineGraph.yAxisRange = @(2500);
    lineGraph.yAxisSuffix = @"";
    lineGraph.xAxisValues = @[
                              @{ @1 : @"00:00" },
                              @{ @2 : @"00:30" },
                              @{ @3 : @"01:00" },
                              @{ @4 : @"01:30" },
                              @{ @5 : @"02:00" },
                              @{ @6 : @"02:30" },
                              @{ @7 : @"03:00" },
                              @{ @8 : @"04:00" },
                              @{ @9 : @"04:30" },
                              @{ @10 : @"05:00" },
                              @{ @11 : @"05:30" },
                              @{ @13 : @"06:00" },
                              @{ @14 : @"06:30" },
                              @{ @15 : @"07:00" },
                              @{ @16 : @"07:30" },
                              @{ @17 : @"08:00" },
                              @{ @18 : @"08:30" },
                              @{ @19 : @"09:00" },
                              @{ @20 : @"09:30" },
                              @{ @21 : @"10:00" },
                              @{ @22 : @"10:30" },
                              @{ @23 : @"11:00" },
                              @{ @24 : @"11:30" },
                              @{ @25 : @"12:00" },
                              @{ @26 : @"12:30" },
                              @{ @27 : @"13:00" },
                              @{ @28 : @"13:30" },
                              @{ @29 : @"14:00" },
                              @{ @30 : @"14:30" },
                              @{ @31 : @"15:00" },
                              @{ @32 : @"15:30" },
                              @{ @33 : @"16:00" },
                              @{ @34 : @"16:30" },
                              @{ @35 : @"17:00" },
                              @{ @36 : @"17:30" },
                              @{ @37 : @"18:00" },
                              @{ @38 : @"18:30" },
                              @{ @39 : @"19:00" },
                              @{ @40 : @"19:30" },
                              @{ @41 : @"20:00" },
                              @{ @42 : @"21:30" },
                              @{ @43 : @"22:00" },
                              @{ @44 : @"22:30" },
                              @{ @45 : @"23:00" },
                              @{ @46 : @"23:30" },
                              @{ @46 : @1500 },
                              ];
    SHPlot *plot1 = [[SHPlot alloc] init];
    plot1.plottingPointsLabels = [labelArray copy];
    plot1.plottingValues = @[
                             @{ @1 : valueArray[0] },
                             @{ @2 : valueArray[1] },
                             @{ @3 : valueArray[2] },
                             @{ @4 : valueArray[3] },
                             @{ @5 : valueArray[4] },
                             @{ @6 : valueArray[5] },
                             @{ @7 : valueArray[6] },
                             @{ @8 : valueArray[7] },
                             @{ @9 : valueArray[8] },
                             @{ @10 : valueArray[9] },
                             @{ @11 : valueArray[10] },
                             @{ @13 : valueArray[11] },
                             @{ @14 : valueArray[12] },
                             @{ @15 : valueArray[13] },
                             @{ @16 : valueArray[14] },
                             @{ @17 : valueArray[15] },
                             @{ @18 : valueArray[16] },
                             @{ @19 : valueArray[17] },
                             @{ @20 : valueArray[18] },
                             @{ @21 : valueArray[19] },
                             @{ @22 : valueArray[20] },
                             @{ @23 : valueArray[21] },
                             @{ @24 : valueArray[22] },
                             @{ @25 : valueArray[23] },
                             @{ @26 : valueArray[24] },
                             @{ @27 : valueArray[25] },
                             @{ @28 : valueArray[26] },
                             @{ @29 : valueArray[27] },
                             @{ @30 : valueArray[28] },
                             @{ @31 : valueArray[29] },
                             @{ @32 : valueArray[30] },
                             @{ @33 : valueArray[31] },
                             @{ @34 : valueArray[32] },
                             @{ @35 : valueArray[33] },
                             @{ @36 : valueArray[34] },
                             @{ @37 : valueArray[35] },
                             @{ @38 : valueArray[36] },
                             @{ @39 : valueArray[37] },
                             @{ @40 : valueArray[38] },
                             @{ @41 : valueArray[39] },
                             @{ @42 : valueArray[40] },
                             @{ @43 : valueArray[41] },
                             @{ @44 : valueArray[42] },
                             @{ @45 : valueArray[43] },
                             @{ @46 : valueArray[44] },
                             @{ @46 : valueArray[45] },
                             ];

    NSDictionary *plotThemeAttributes = @{
                                           kPlotFillColorKey : [UIColor colorWithRed:250.0/255.0 green:174.0/255.0 blue:59.0/255.0 alpha:0.2],
                                           kPlotStrokeWidthKey : @2,
                                           kPlotStrokeColorKey : [UIColor colorWithRed:250.0/255.0 green:174.0/255.0 blue:59.0/255.0 alpha:1],
                                           kPlotPointFillColorKey : [UIColor colorWithRed:250.0/255.0 green:174.0/255.0 blue:59.0/255.0 alpha:1],
                                           kPlotPointValueFontKey : [UIFont fontWithName:@"TrebuchetMS" size:18]
                                           };
    
    plot1.plotThemeAttributes = plotThemeAttributes;
    [lineGraph addPlot:plot1];
    
    [lineGraph setupTheView];
    [scroll addSubview:lineGraph];
    
    //加载纵轴坐标
    numBoardView = [[UIView alloc]initWithFrame:CGRectMake(0, -40, 50, 568)];
    numBoardView.backgroundColor = [UIColor clearColor];
    [backSroll addSubview:numBoardView];
    
    for (UILabel *tempLabel in lineGraph.YPlots) {
        tempLabel.frame = CGRectMake(tempLabel.frame.origin.x, tempLabel.frame.origin.y+100, tempLabel.frame.size.width, tempLabel.frame.size.height);
        [numBoardView addSubview:tempLabel];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return historyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    HistoryCell *cell = (HistoryCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"HistoryCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = AIR_GRAY;
        cell.backView.backgroundColor = [UIColor whiteColor];
        cell.backView.layer.cornerRadius = 5;
        cell.backView.layer.borderColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3].CGColor;
        cell.backView.layer.borderWidth = 0.5;
        cell.addressView.userInteractionEnabled = NO;
        if (dataType==0) {
            cell.unitLabel.text = @"ug/m³";
        } else if (dataType==2) {
            cell.unitLabel.text = @"ppm";
        } else if (dataType==1) {
            cell.unitLabel.text = @"ppm";
        }
        
    }
    HistoryModel *tempModel = historyArray[indexPath.row];
    cell.dateLabel.text = [LRTools turnTimeByTime:tempModel.historyDate];
    cell.valueLabel.text = [NSString stringWithFormat:@"%i",(int)tempModel.historyValue.floatValue];
    cell.valueLabel.textColor = [LRTools setColorForValue:tempModel.historyValue AndType:dataType];
    cell.addressView.text = tempModel.historyAddress;
    
    return cell;
}

#pragma mark - UIScrollViewDelegate

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (refreshHeaderView) {
        [refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (refreshHeaderView) {
        [refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
}


#pragma mark - EGORefreshTableDelegate
- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos {
    
    if (historyTable.alpha==1) {
        [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:historyTable];
        
        NSString *historyType;
        if (dataType==0) {
            historyType = @"pm25";
        } else if (dataType==1) {
            historyType = @"co2";
        } else if (dataType==2) {
            historyType = @"hcho";
        }
        dispatch_async (dispatch_get_global_queue (DISPATCH_QUEUE_PRIORITY_LOW ,0),^{
            
            NSString *lastTime;
            if (dataType==0) {
                lastTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"lastPMHistory"];
            } else if (dataType==2) {
                lastTime = [[NSUserDefaults standardUserDefaults]objectForKey:@"lastHOCOHistory"];
            }
            NSDictionary *resposeDic = [[LRHttpManager createHttpManager]queryHistoryByPhone:[LRUserManager createManager].userPhone AndTime:lastTime AndType:historyType AndPage:@"0"];
            
            NSArray *tempArray = [resposeDic objectForKey:@"contents"];
            
            for (NSDictionary *tempDic in tempArray) {
                HistoryModel *tempModel = [[HistoryModel alloc]init];
                
                tempModel.historyDate = [tempDic objectForKey:@"sendtime"];
                if ([[tempDic objectForKey:@"placediy"] isEqualToString:@"无自定义地址"]||((NSString*)[tempDic objectForKey:@"placediy"]).length<=1) {
                    tempModel.historyAddress = [tempDic objectForKey:@"address"];
                } else {
                    tempModel.historyAddress = [tempDic objectForKey:@"placediy"];
                }
                tempModel.historyID = [tempDic objectForKey:@"\"geotable_id\""];
                if (dataType==0) {
                    tempModel.historyValue = [tempDic objectForKey:@"pm"];
                } else if (dataType==1) {
                    
                } else if (dataType==2) {
                    tempModel.historyValue = [tempDic objectForKey:@"hcho"];
                }
                
                LRDatabaseManager *manager=[LRDatabaseManager createDatabase];
                [manager.dataQueue inDatabase:^(FMDatabase *db){
                    [db open];
                    
                    BOOL result = [db executeUpdate:@"insert into HistoryTable(UserPhone,HistoryDate,HistoryValue,HistoryAddress,HistoryType) values(?,?,?,?,?)",[LRUserManager createManager].userPhone,tempModel.historyDate,tempModel.historyValue,tempModel.historyAddress,[NSNumber numberWithInt:dataType]];
                    NSLog(@"历史记录插入数据库%@",result?@"成功":@"失败");
                    [db close];
                }];
                
                NSLog(@"!!!%@",tempDic);
            }
            
            dispatch_async (dispatch_get_main_queue(),^{
                if ([[resposeDic objectForKey:@"code"] integerValue]==0) {
                    NSLog(@"获取历史记录成功");
                    [self finishReloadingData];
                    if (dataType==0) {
                        [[NSUserDefaults standardUserDefaults]setObject:[LRTools getNowTime] forKey:@"lastPMHistory"];
                    } else if (dataType==2) {
                        [[NSUserDefaults standardUserDefaults]setObject:[LRTools getNowTime] forKey:@"lastHOCOHistory"];
                    }
                    
                    needReload = YES;
                } else {
                    NSLog(@"获取历史记录失败");
                    MBProgressHUD *shortHub = [[MBProgressHUD alloc]initWithView:self.view];
                    [self.view addSubview:shortHub];
                    [shortHub setLabelText:@"获取历史记录失败,请稍后再试"];
                    [shortHub setMode:MBProgressHUDModeText];
                    [shortHub hide:YES afterDelay:1];
                    [shortHub show:YES];
                    [self finishReloadingData];
                    needReload = NO;
                }
            });
        });
    } else {
        [self performSelector:@selector(finishReloadingData) withObject:nil afterDelay:0.5];
    }
    
}
- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view {
    
    return NO;
}

- (void)finishReloadingData{
	
    if (historyTable.alpha==1) {
        if (refreshHeaderView) {
            [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:historyTable];
        }
        [historyArray removeAllObjects];
        historyArray = [[[LRDatabaseManager createDatabase]getHistoryArrayByPhone:[LRUserManager createManager].userPhone AndType:dataType] mutableCopy];
        
        if (needReload) {
            [self performSelector:@selector(reloadTableView) withObject:nil afterDelay:0.5];
        }
    } else {
        if (refreshHeaderView) {
            [refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:backSroll];
        }
    }
}

- (void)reloadTableView {
    [historyTable reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 分段切换
- (void)changeSegmented:(LRSegmentedControl*)sender {
    
    if (sender.selectedSegmentIndex==0) {
        historyTable.alpha = 1;
        backSroll.alpha = 0;
        [historyTable addSubview:refreshHeaderView];
    } else {
        backSroll.alpha = 1;
        historyTable.alpha = 0;
        [backSroll addSubview:refreshHeaderView];
    }
}



@end
